<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑试卷' : '创建试卷' }}</span>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="试卷标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入试卷标题"></el-input>
        </el-form-item>
        
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="form.educationLevel" placeholder="请选择教育阶段" @change="handleEducationLevelChange" style="width: 100%">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择学科" filterable style="width: 100%">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="考试时长" prop="duration">
          <el-input-number v-model="form.duration" :min="1" :max="300"></el-input-number>
          <span class="unit-text">分钟</span>
        </el-form-item>
        
        <el-form-item label="试卷说明">
          <el-input type="textarea" v-model="form.description" placeholder="请输入试卷说明" :rows="4"></el-input>
        </el-form-item>
        
        <el-divider content-position="left">试卷题目</el-divider>
        
        <!-- 题型分组 -->
        <div v-for="(section, sectionIndex) in sections" :key="sectionIndex" class="question-section">
          <div class="section-header">
            <h3>{{ section.name }}</h3>
            <div class="section-actions">
              <el-button type="text" @click="addQuestion(section.type)">添加题目</el-button>
            </div>
          </div>
          
          <el-empty v-if="section.questions.length === 0" description="暂无题目"></el-empty>
          
          <el-table
            v-else
            :data="section.questions"
            style="width: 100%"
            border>
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center">
            </el-table-column>
            
            <el-table-column
              prop="content"
              label="题目内容"
              min-width="300">
              <template slot-scope="scope">
                <div class="question-content" v-html="formatContent(scope.row.content)"></div>
              </template>
            </el-table-column>
            
            <el-table-column
              prop="score"
              label="分值"
              width="100"
              align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.score"
                  :min="1"
                  :max="100"
                  size="mini"
                  @change="calculateTotalScore">
                </el-input-number>
              </template>
            </el-table-column>
            
            <el-table-column
              label="操作"
              width="120"
              align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="removeQuestion(section.type, scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="total-score">
          <span class="label">总分：</span>
          <span class="score">{{ totalScore }}</span>
        </div>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 选择题目对话框 -->
    <el-dialog
      title="选择题目"
      :visible.sync="dialogVisible"
      width="80%">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline" size="small">
        <el-form-item label="难度">
          <el-select v-model="queryParams.difficulty" placeholder="请选择难度" clearable>
            <el-option label="简单" :value="1"></el-option>
            <el-option label="中等" :value="2"></el-option>
            <el-option label="困难" :value="3"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="关键词">
          <el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="getQuestionList">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table
        v-loading="loading"
        :data="questionList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="50">
        </el-table-column>
        
        <el-table-column
          prop="content"
          label="题目内容"
          min-width="300">
          <template slot-scope="scope">
            <div class="question-content" v-html="formatContent(scope.row.content)"></div>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="difficultyName"
          label="难度"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-tag :type="getDifficultyType(scope.row.difficulty)">{{ scope.row.difficultyName }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectQuestions">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getPaperDetail, addPaper, updatePaper } from '@/api/paper';
import { getQuestionList } from '@/api/question';
import { getAllSubjects } from '@/api/subject';

export default {
  name: 'PaperEdit',
  data() {
    return {
      isEdit: false,
      paperId: null,
      form: {
        title: '',
        description: '',
        duration: 60,
        educationLevel: undefined,
        subjectId: undefined
      },
      rules: {
        title: [
          { required: true, message: '请输入试卷标题', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入考试时长', trigger: 'blur' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ]
      },
      subjectOptions: [],
      allSubjects: [],
      sections: [
        { type: 1, name: '一、单选题', questions: [] },
        { type: 2, name: '二、多选题', questions: [] },
        { type: 3, name: '三、判断题', questions: [] },
        { type: 4, name: '四、填空题', questions: [] },
        { type: 5, name: '五、简答题', questions: [] }
      ],
      totalScore: 0,
      dialogVisible: false,
      currentQuestionType: null,
      loading: false,
      questionList: [],
      selectedQuestions: [],
      queryParams: {
        page: 1,
        size: 10,
        type: undefined,
        difficulty: undefined,
        subjectId: undefined,
        educationLevel: undefined,
        keyword: ''
      },
      total: 0
    };
  },
  created() {
    this.paperId = this.$route.params.id;
    this.isEdit = !!this.paperId;
    
    this.getSubjects();
    
    if (this.isEdit) {
      this.getPaperDetail();
    }
  },
  methods: {
    // 获取学科列表
    getSubjects() {
      getAllSubjects().then(response => {
        this.allSubjects = response.data;
        this.filterSubjectsByLevel(this.form.educationLevel);
      });
    },
    // 根据教育阶段筛选学科
    filterSubjectsByLevel(level) {
      if (!level || !this.allSubjects || this.allSubjects.length === 0) {
        this.subjectOptions = this.allSubjects.map(subject => ({
          value: subject.id,
          label: subject.name
        }));
        return;
      }
      
      const filteredSubjects = this.allSubjects.filter(subject => subject.level === level);
      this.subjectOptions = filteredSubjects.map(subject => ({
        value: subject.id,
        label: subject.name
      }));
      
      // 如果当前选中的学科不在筛选结果中，清空选择
      if (this.form.subjectId) {
        const exists = filteredSubjects.some(subject => subject.id === this.form.subjectId);
        if (!exists) {
          this.form.subjectId = undefined;
        }
      }
    },
    // 教育阶段变化时触发
    handleEducationLevelChange(level) {
      this.filterSubjectsByLevel(level);
    },
    // 获取试卷详情
    getPaperDetail() {
      getPaperDetail(this.paperId).then(response => {
        const paperData = response.data;
        this.form = {
          title: paperData.title,
          description: paperData.description,
          duration: paperData.duration,
          educationLevel: paperData.educationLevel,
          subjectId: paperData.subjectId
        };
        
        // 加载试卷题目
        if (paperData.questions && paperData.questions.length > 0) {
          // 按题型分组
          for (const question of paperData.questions) {
            const section = this.sections.find(s => s.type === question.questionType);
            if (section) {
              section.questions.push({
                id: question.questionId,
                content: question.content,
                score: question.score,
                options: question.options,
                answer: question.answer,
                analysis: question.analysis
              });
            }
          }
          
          this.calculateTotalScore();
        }
        
        // 加载学科选项
        this.filterSubjectsByLevel(paperData.educationLevel);
      });
    },
    // 添加题目
    addQuestion(type) {
      this.currentQuestionType = type;
      this.queryParams.type = type;
      this.queryParams.subjectId = this.form.subjectId;
      this.queryParams.educationLevel = this.form.educationLevel;
      this.dialogVisible = true;
      this.getQuestionList();
    },
    // 删除题目
    removeQuestion(type, index) {
      const section = this.sections.find(s => s.type === type);
      if (section) {
        section.questions.splice(index, 1);
        this.calculateTotalScore();
      }
    },
    // 计算总分
    calculateTotalScore() {
      let total = 0;
      for (const section of this.sections) {
        for (const question of section.questions) {
          total += question.score;
        }
      }
      this.totalScore = total;
    },
    // 获取题目列表
    getQuestionList() {
      if (!this.form.educationLevel || !this.form.subjectId) {
        this.$message.warning('请先选择教育阶段和学科');
        return;
      }
      
      this.loading = true;
      this.queryParams.educationLevel = this.form.educationLevel;
      this.queryParams.subjectId = this.form.subjectId;
      
      getQuestionList(this.queryParams).then(response => {
        this.questionList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
        
        // 标记已选中的题目
        const section = this.sections.find(s => s.type === this.currentQuestionType);
        if (section) {
          const existingIds = section.questions.map(q => q.id);
          this.$nextTick(() => {
            this.questionList.forEach(question => {
              if (existingIds.includes(question.id)) {
                this.$refs.table.toggleRowSelection(question, true);
              }
            });
          });
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    // 查询按钮点击事件
    handleQuery() {
      this.queryParams.page = 1;
      this.getQuestionList();
    },
    // 重置按钮点击事件
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        type: this.currentQuestionType,
        difficulty: undefined,
        subjectId: this.form.subjectId,
        educationLevel: this.form.educationLevel,
        keyword: ''
      };
      this.getQuestionList();
    },
    // 每页条数改变时触发
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.getQuestionList();
    },
    // 当前页改变时触发
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getQuestionList();
    },
    // 选择题目变化时触发
    handleSelectionChange(selection) {
      this.selectedQuestions = selection;
    },
    // 确认选择题目
    confirmSelectQuestions() {
      const section = this.sections.find(s => s.type === this.currentQuestionType);
      if (section) {
        // 清空原有题目
        section.questions = [];
        
        // 添加选中的题目
        for (const question of this.selectedQuestions) {
          section.questions.push({
            id: question.id,
            content: question.content,
            score: 5, // 默认分值
            options: question.options,
            answer: question.answer,
            analysis: question.analysis
          });
        }
        
        this.calculateTotalScore();
        this.dialogVisible = false;
      }
    },
    // 格式化题目内容
    formatContent(content) {
      if (!content) return '';
      // 截取前100个字符，避免内容过长
      return content.length > 100 ? content.substring(0, 100) + '...' : content;
    },
    // 获取难度标签类型
    getDifficultyType(difficulty) {
      switch (difficulty) {
        case 1: return 'success';
        case 2: return 'warning';
        case 3: return 'danger';
        default: return '';
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 检查是否有题目
          const hasQuestions = this.sections.some(section => section.questions.length > 0);
          if (!hasQuestions) {
            this.$message.warning('请至少添加一道题目');
            return;
          }
          
          const formData = { ...this.form };
          formData.totalScore = this.totalScore;
          
          // 处理题目
          formData.questions = [];
          let questionNumber = 1;
          
          for (const section of this.sections) {
            for (const question of section.questions) {
              formData.questions.push({
                questionId: question.id,
                score: question.score,
                questionNumber: questionNumber++,
                questionType: section.type
              });
            }
          }
          
          if (this.isEdit) {
            formData.id = this.paperId;
            updatePaper(formData).then(() => {
              this.$message.success('更新成功');
              this.$router.push('/papers');
            }).catch(() => {
              this.$message.error('更新失败');
            });
          } else {
            addPaper(formData).then(() => {
              this.$message.success('创建成功');
              this.$router.push('/papers');
            }).catch(() => {
              this.$message.error('创建失败');
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      this.$router.push('/papers');
    }
  }
};
</script>

<style scoped>
.question-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-header h3 {
  margin: 0;
}

.question-content {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.total-score {
  margin: 20px 0;
  font-size: 16px;
  text-align: right;
}

.total-score .label {
  font-weight: bold;
}

.total-score .score {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.unit-text {
  margin-left: 10px;
}
</style> 